    import sys
import os
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QMessageBox
from PyQt5.QtCore import QProcess

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.setWindowTitle("外部程序启动器")
        self.setGeometry(100, 100, 300, 200)
        
        self.button = QPushButton("启动外部程序", self)
        self.button.setGeometry(100, 80, 100, 40)
        self.button.clicked.connect(self.start_external_program)
        
        self.process = None
    
    def start_external_program(self):
        if self.process is None or self.process.state() == QProcess.NotRunning:
            try:
                self.process = QProcess(self)
                script_dir = os.path.dirname(os.path.abspath(__file__))
                exe_path = os.path.join(script_dir, "Aoe_Qt.exe")
                
                if not os.path.exists(exe_path):
                    QMessageBox.critical(self, "错误", f"未找到程序: {exe_path}")
                    return
                
                self.process.setWorkingDirectory(script_dir)
                self.process.start(exe_path)
                self.button.setText("停止程序")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"启动失败: {str(e)}")
        else:
            self.process.terminate()
            if not self.process.waitForFinished(1000):
                self.process.kill()
            self.process = None
            self.button.setText("启动外部程序")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())